package dating.controller;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dating.model.Message;
import dating.model.User;
import dating.service.MessageServiceLocal;

/**
 * Servlet implementation class Message
 */
public class Messages extends Application {
	private static final long serialVersionUID = 1L;
    
	@EJB 
	private MessageServiceLocal messageService;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Messages() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!isLogged(request)){
			response.sendRedirect("login");
			return;
		}
		List<Message> messages = messageService.findAllByUserId(getLoggedUser(request).getId());
		if(messages != null && messages.size() > 0) {
			for(Message msg: messages) {
				msg.setRead(true);
			}
		}
		request.setAttribute("messages", messages);
		render("messages.jsp", request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!isLogged(request)){
			response.sendRedirect("login");
			return;
		}
		String messageBody = request.getParameter("message_body");
		long senderId = getLoggedUser(request).getId();
		long recepientId = Long.parseLong(request.getParameter("recepient_id"));
		User sender = userService.findByPK(senderId);
		User recepient = userService.findByPK(recepientId);
		messageService.sendMessage(messageBody, sender, recepient);
		response.sendRedirect("profile?id=" + recepientId);
	}

}
